<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TodoList 案例</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Arial', sans-serif;
        }
        body {
            background-color: #f5f5f5;
            padding: 20px;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #333;
        }
        .input-group {
            display: flex;
            margin-bottom: 20px;
        }
        #new-todo {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            font-size: 16px;
        }
        #add-btn {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
            font-size: 16px;
        }
        #add-btn:hover {
            background-color: #45a049;
        }
        .todo-list {
            list-style: none;
        }
        .todo-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .todo-item:hover {
            background-color: #f9f9f9;
        }
        .todo-checkbox {
            margin-right: 10px;
            cursor: pointer;
        }
        .todo-title {
            flex: 1;
            font-size: 16px;
        }
        .todo-title.completed {
            text-decoration: line-through;
            color: #888;
        }
        .todo-actions {
            display: flex;
            gap: 10px;
        }
        .edit-btn, .delete-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .edit-btn {
            background-color: #2196F3;
            color: white;
        }
        .edit-btn:hover {
            background-color: #0b7dda;
        }
        .delete-btn {
            background-color: #f44336;
            color: white;
        }
        .delete-btn:hover {
            background-color: #d32f2f;
        }
        .edit-input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>TodoList</h1>
        <div class="input-group">
            <input type="text" id="new-todo" placeholder="输入新的待办事项...">
            <button id="add-btn">添加</button>
        </div>
        <ul class="todo-list" id="todo-list">
            <!-- 待办事项将在这里动态生成 -->
        </ul>
    </div>

    <script>
        // 获取DOM元素
        const todoList = document.getElementById('todo-list');
        const newTodoInput = document.getElementById('new-todo');
        const addBtn = document.getElementById('add-btn');

        // 后端API基础URL
        const API_BASE_URL = 'http://localhost:3001/api/todos';

        // 加载待办事项
        async function loadTodos() {
            try {
                const response = await fetch(API_BASE_URL);
                if (!response.ok) throw new Error('加载失败');
                const todos = await response.json();
                renderTodos(todos);
            } catch (error) {
                alert(error.message);
            }
        }

        // 渲染待办事项列表
        function renderTodos(todos) {
            todoList.innerHTML = '';
            todos.forEach(todo => {
                const li = document.createElement('li');
                li.className = 'todo-item';
                li.dataset.id = todo.id;

                li.innerHTML = `
                    <input type="checkbox" class="todo-checkbox" ${todo.done ? 'checked' : ''}>
                    <span class="todo-title ${todo.done ? 'completed' : ''}">${todo.title}</span>
                    <div class="todo-actions">
                        <button class="edit-btn">编辑</button>
                        <button class="delete-btn">删除</button>
                    </div>
                `;

                todoList.appendChild(li);

                // 添加事件监听器
                const checkbox = li.querySelector('.todo-checkbox');
                const editBtn = li.querySelector('.edit-btn');
                const deleteBtn = li.querySelector('.delete-btn');
                const titleSpan = li.querySelector('.todo-title');

                // 切换完成状态
                checkbox.addEventListener('change', async () => {
                    try {
                        const response = await fetch(`${API_BASE_URL}/${todo.id}`, {
                            method: 'PATCH',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ done: checkbox.checked })
                        });
                        
                        if (!response.ok) throw new Error('更新失败');
                        
                        titleSpan.classList.toggle('completed', checkbox.checked);
                    } catch (error) {
                        alert(error.message);
                        checkbox.checked = !checkbox.checked; // 恢复原状态
                    }
                });

                // 编辑待办事项
                editBtn.addEventListener('click', () => {
                    const currentTitle = titleSpan.textContent;
                    const input = document.createElement('input');
                    input.type = 'text';
                    input.className = 'edit-input';
                    input.value = currentTitle;
                    
                    titleSpan.replaceWith(input);
                    input.focus();

                    const handleEdit = async () => {
                        const newTitle = input.value.trim();
                        if (newTitle && newTitle !== currentTitle) {
                            try {
                                const response = await fetch(`${API_BASE_URL}/${todo.id}`, {
                                    method: 'PATCH',
                                    headers: {
                                        'Content-Type': 'application/json',
                                    },
                                    body: JSON.stringify({ title: newTitle })
                                });
                                
                                if (!response.ok) throw new Error('更新失败');
                                
                                titleSpan.textContent = newTitle;
                            } catch (error) {
                                alert(error.message);
                            }
                        }
                        input.replaceWith(titleSpan);
                    };

                    input.addEventListener('blur', handleEdit);
                    input.addEventListener('keypress', (e) => {
                        if (e.key === 'Enter') handleEdit();
                    });
                });

                // 删除待办事项
                deleteBtn.addEventListener('click', async () => {
                    if (!confirm('确定要删除这个待办事项吗？')) return;
                    
                    try {
                        const response = await fetch(`${API_BASE_URL}/${todo.id}`, {
                            method: 'DELETE'
                        });
                        
                        if (!response.ok) throw new Error('删除失败');
                        
                        li.remove();
                    } catch (error) {
                        alert(error.message);
                    }
                });
            });
        }

        // 添加新的待办事项
        addBtn.addEventListener('click', async () => {
            const title = newTodoInput.value.trim();
            if (!title) {
                alert('请输入待办事项内容');
                return;
            }

            try {
                const response = await fetch(API_BASE_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ title })
                });
                
                if (!response.ok) throw new Error('添加失败');
                
                const newTodo = await response.json();
                newTodoInput.value = '';
                loadTodos(); // 重新加载列表以确保顺序正确
            } catch (error) {
                alert(error.message);
            }
        });

        // 初始化加载
        loadTodos();
    </script>
</body>
</html>